package configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import proxy.IRequestProxy;
import proxy.LocalRequestProxy;
import proxy.RemoteRequestProxy;

/**
 * 自定义配置类
 *
 * @author wxf
 */
@Configuration
@EnableConfigurationProperties(RequestTypeConfiguration.class)
public class RequestProxyConfiguration {
	@Autowired
	private RequestTypeConfiguration requestTypeConfiguration;
	@Autowired
	private RequestMappingHandlerMapping requestMappingHandlerMapping;
	@Autowired
	private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
	private Logger logger = LoggerFactory.getLogger(RequestProxyConfiguration.class);

	@Bean
	@LoadBalanced
	public RestTemplate getRestTemplate() {
		return new RestTemplate();
	}

	@Bean
	public SpringContextUtil springContextUtil() {
		return new SpringContextUtil();
	}


	/**
	 * 根据条件生成 代理类
	 */
	@Bean
	public IRequestProxy requestProxy(RestTemplate restTemplate) {
		if (requestTypeConfiguration.getType().equalsIgnoreCase(RequestTypeConfiguration.LOCAL_PROXY_TYPE)) {
			return new LocalRequestProxy(requestMappingHandlerAdapter, requestMappingHandlerMapping);
		} else {
			return new RemoteRequestProxy(restTemplate);
		}
	}
}
